import { createStore, applyMiddleware, compose } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { persistStore, persistReducer } from 'redux-persist';
import Taro from '@tarojs/taro';
import rootReducer from './reducers';

const composeEnhancers =
    typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
        ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
        : compose;

const middlewares = [thunkMiddleware];

if (process.env.NODE_ENV === 'development' && process.env.TARO_ENV !== 'quickapp') {
    middlewares.push(require('redux-logger').createLogger());
}

const enhancer = composeEnhancers(applyMiddleware(...middlewares));

const persistConfig = {
    key: 'taro',
    debounce: 500,
    storage: {
        async getItem(key) {
            return Promise.resolve().then(() => {
                return Taro.getStorageSync(key);
            });
        },
        async setItem(key, data) {
            return Promise.resolve().then(() => {
                return Taro.setStorage({ key, data });
            });
        },
        async removeItem(key) {
            return Promise.resolve().then(() => {
                return Taro.removeStorage({ key });
            });
        },
        async clear() {
            return Promise.resolve().then(() => {
                return Taro.clearStorage();
            });
        }
    }
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export default () => {
    const store = createStore(persistedReducer, enhancer);
    const persistor = persistStore(store);
    return { store, persistor };
};
